<template>
  <div>
    <div>
      <van-search
        v-model="searchvalue"
        class="searchclose"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
      >
        <template #action>
          <div @click="onSearch">取消</div>
        </template>
      </van-search>
    </div>
    <div>
      <!-- 搜索结果组件 -->
      <search-result-vue v-if="searchResultShow" :searchvalue="searchvalue" />
      <!-- 搜索联想词 -->
      <search-suggestion-vue
        v-else-if="searchvalue"
        :searchvalue="searchvalue"
        @keywordFn="keywordFn"
      />
      <!-- 搜索历史 -->
      <search-history-vue
        v-else
        :searchHistoryList="searchHistoryList"
        @deleteAll="searchHistoryList = []"
        @openresult="openresult"
      />
    </div>
  </div>
</template>
<script>
import searchHistoryVue from "./component/searchHistory.vue";
import searchResultVue from "./component/searchResult.vue";
import searchSuggestionVue from "./component/searchSuggestion.vue";
import { getItem, setItem } from "@/utils/storage";
export default {
  components: {
    searchHistoryVue,
    searchResultVue,
    searchSuggestionVue,
  },
  data() {
    return {
      searchvalue: "", //搜索框的值
      searchResultShow: false, //当有了搜索结果才展示
      searchHistoryList: getItem("SEARCHHISTORY") || [], //历史记录集合 每次获取一下本地的缓存的
    };
  },
  methods: {
    onSearch() {
      this.$router.push("/home");
    },
    keywordFn(val) {
      this.searchvalue = val;
      this.searchResultShow = true;
      //历史记录 添加 然后再存入缓存

      //判断 历史搜索有没有重复的 如果有就不用存储了

      if (this.searchHistoryList.indexOf(val) != -1) {
        this.searchHistoryList.splice(this.searchHistoryList.indexOf(val), 1);
      } else {
        this.searchHistoryList.unshift(val);
        //搜索结果组件展示
        this.searchResultShow = true;
      }
    },
    //根据从历史记录返回的结果 进行搜索
    openresult(item) {
      this.searchResultShow = true;
      this.searchvalue = item;
    },
  },
  watch: {
    searchHistoryList: {
      handler(newVal) {
        setItem("SEARCHHISTORY", newVal);
      },
    },
    searchvalue(newVal) {
      if (newVal.trim().length == 0) {
        this.searchResultShow = false;
      }
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .searchclose {
  .van-search__action {
    color: #fff;
  }
}
</style>
